import { useState, useRef, useEffect } from 'react';
import { ChatOpenAI } from "@langchain/openai";
import { 
  ChatPromptTemplate,
  PromptTemplate, 
  PipelinePromptTemplate
 } from "@langchain/core/prompts";
import { LLMChain } from "langchain/chains";
import ReactMarkdownComponent from './components/reactMarkdown';

export default function PromptCombin() {
  const [messages, setMessages] = useState<Array<{role: string, content: string}>>([]);
  const [loading, setLoading] = useState(false);
  // 添加用户可配置变量状态
  const [person, setPerson] = useState("兽医");
  const [exampleQ, setExampleQ] = useState("小猫总是尿床怎么办?");
  const [exampleA, setExampleA] = useState("有可能是蓄意报复,但是也可能是那里残留很多主人的气味,小猫会感到很舒服,所以会一直尿床,建议你把那里彻底清理干净,并且不要让小猫靠近那里,以免再次发生类似的事情。");
  const [userInput, setUserInput] = useState("");
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  // 创建模型实例
  const chatModel = new ChatOpenAI({
    modelName: "gpt-3.5-turbo",
    configuration: {
      apiKey: 'xxx',
      baseURL: 'https://xxx'
    },
  });

  // 组合提示
  const fullPrompt = PromptTemplate.fromTemplate(
    `{introduction}
    {example}
    {start}`
  );
  // 组合提示-1
  const introductionPrompt = PromptTemplate.fromTemplate(
    `你正在冒充 {person}，他/她是一位非常聪明和有见地的人。你将用他的口吻回答问题`
  );
  // 组合提示-2
  const examplePrompt =
      PromptTemplate.fromTemplate(`这里是一个互动的例子:
    Q: {example_q}
    A: {example_a}`
  );
  // 组合提示-3
  const startPrompt = PromptTemplate.fromTemplate(`现在, 来试试吧!
    Q: {input}
    A:`
  );
  // 组装所有提示模板
  const composedPrompt = new PipelinePromptTemplate({
    pipelinePrompts: [
      {
        name: "introduction",
        prompt: introductionPrompt,
      },
      {
        name: "example",
        prompt: examplePrompt,
      },
      {
        name: "start",
        prompt: startPrompt,
      },
    ],
    finalPrompt: fullPrompt,
  });

  // 修改组合提示模板格式化逻辑
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!userInput) return;

    setLoading(true);
    try {
      // 添加用户消息到聊天记录
      setMessages(prev => [...prev, {
        role: 'user',
        content: userInput
      }]);

      // 使用用户配置的变量格式化提示
      const formattedPrompt = await composedPrompt.format({
        person,
        example_q: exampleQ,
        example_a: exampleA,
        input: userInput,
      });

      // 创建临时提示模板并调用LLM
      const tempPrompt = PromptTemplate.fromTemplate(formattedPrompt);
      const chain = new LLMChain({ llm: chatModel, prompt: tempPrompt });
      const response = await chain.call({});

      // 添加AI回复到聊天记录
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: response.text
      }]);

      // 清空输入
      setUserInput("");
    } catch (error) {
      console.error("调用出错:", error);
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: "抱歉，处理请求时出错，请稍后重试"
      }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      maxWidth: '800px',
      margin: '0 auto',
      padding: '20px',
      fontFamily: 'Arial, sans-serif'
    }}>
      <h1 style={{ textAlign: 'center', color: '#333' }}>组合提示模板聊天</h1>

      {/* 变量配置区域 */}
      <div style={{ marginBottom: '20px', padding: '15px', border: '1px solid #e0e0e0', borderRadius: '8px', backgroundColor: '#f5f5f5' }}>
        <h3 style={{ marginTop: 0, color: '#555' }}>提示变量配置</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>角色</label>
            <input
              type="text"
              value={person}
              onChange={(e) => setPerson(e.target.value)}
              style={{ width: '90%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }}
              placeholder="输入角色名称"
            />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>示例问题</label>
            <input
              type="text"
              value={exampleQ}
              onChange={(e) => setExampleQ(e.target.value)}
              style={{ width: '90%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }}
              placeholder="输入示例问题"
            />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>示例回答</label>
            <input
              type="text"
              value={exampleA}
              onChange={(e) => setExampleA(e.target.value)}
              style={{ width: '90%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }}
              placeholder="输入示例回答"
            />
          </div>
        </div>
      </div>

      {/* 聊天消息区域 */}
      <div
        ref={chatContainerRef}
        style={{
          height: '350px',
          border: '1px solid #e0e0e0',
          borderRadius: '8px',
          marginBottom: '20px',
          overflowY: 'auto',
          backgroundColor: '#f9f9f9'
        }}
      >
        {messages.length === 0 ? (
          <div style={{
            textAlign: 'center',
            color: '#666',
            marginTop: '150px'
          }}>
            开始您的第一次咨询吧！
          </div>
        ) : (
          messages.map((msg, index) => (
            <div key={index} style={{
              margin: '10px 0',
              display: 'flex',
              flexDirection: msg.role === 'user' ? 'row-reverse' : 'row'
            }}>
              <div style={{
                maxWidth: '70%',
                padding: '12px 15px',
                borderRadius: '18px',
                backgroundColor: msg.role === 'user' ? '#dcf8c6' : '#ffffff',
                border: '1px solid #e0e0e0',
                boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
              }}>
                <strong style={{ color: msg.role === 'user' ? '#075e54' : '#333' }}>
                  {msg.role === 'user' ? '我' : 'AI'}:
                </strong>
                <div style={{ wordBreak: 'break-word', marginTop: '5px' }}>
                  {/* {msg.content} */}
                  <ReactMarkdownComponent content={msg.content} />
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 用户输入区域 */}
      <form onSubmit={handleSubmit} style={{ display: 'flex', gap: '10px' }}>
        <input
          type="text"
          value={userInput}
          onChange={(e) => setUserInput(e.target.value)}
          style={{ flex: 1, padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }}
          placeholder="输入您的问题..."
        />
        <button
          type="submit"
          disabled={loading || !userInput}
          style={{
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            disabled: { backgroundColor: '#ccc', cursor: 'not-allowed' }
          }}
        >
          {loading ? '思考中...' : '发送'}
        </button>
      </form>
    </div>
  );
}
;
